#!/usr/bin/perl -w

# Extract all plain text from an HTML file

require LWP::UserAgent;
require HTML::Parser;
use URI;
 
 my %inside;
 my $ua = LWP::UserAgent->new;
   $ua->timeout(10);
   $ua->env_proxy;

my $p = HTML::Parser->new(api_version => 3,
                  handlers    => [start => [\&tag, "tagname, '+1',attr"],
                                  end   => [\&tag, "tagname, '-1',attr"],
                                  text  => [\&text, "dtext"],
                                 ],
                  marked_sections => 1,
        );

my $request = shift;
while (@ARGV) {$request .= " " . shift;} 

my $url = URI->new( 'http://www.wolframalpha.com/input/' );
    # makes an object representing the URL
  
 $url->query_form(  # And here the form data pairs:
    'i'    => $request,
  );
  
#my $response = $ua->get($url);
$p->parse($ua->get($url)->decoded_content);
print "\n";
sub tag
{
   my($tag, $num, $attr) = @_;
   $inside{$tag} += $num;
#   print " ";  # not for all tags
   if(($tag eq "img")&& (exists $attr->{alt})){my $text = $attr->{alt}; $text =~ s/\\n/ /g; print $text . "\n";}
}

sub text
{
    return if $inside{script} || $inside{style};
#    if ($inside{fieldset}) {
#      if ($inside{div} && (not $inside{ul}) && (not $inside{span} && (not $inside{label}) && (not $inside{a}))){ print $_[0];}
#      if ($inside{a}) {print $_[0] . "\n";} }
    if ($inside{h2}){
    my $text = $_[0];
    $text =~ s/\\n/ /g;
    print $text . "\n";}

}
